import api from './api';
import authService from './authService';

const BASE_URL = 'http://localhost:8080/api/accounts';

export const accountService = {
  // Get all accounts for the current user
  getAccounts() {
    return api.get(`${BASE_URL}`);
  },

  // Get account details by ID
  getAccountById(accountId) {
    return api.get(`${BASE_URL}/${accountId}`);
  },

  // Get account balance
  getAccountBalance(accountId) {
    return api.get(`${BASE_URL}/${accountId}/balance`);
  },

  // Get account transactions
  getAccountTransactions(accountId, params) {
    return api.get(`${BASE_URL}/${accountId}/transactions`, { params });
  },

  // Transfer money between accounts
  transferMoney(transferData) {
    return api.post(`${BASE_URL}/transfer`, transferData);
  },

  // Open new account
  openNewAccount(accountData) {
    return api.post(`${BASE_URL}/open`, accountData);
  },
  
  // Submit account application
  submitAccountApplication(applicationData) {
    // Double-check that we have the user ID
    if (!applicationData.customerId) {
      const userId = this.extractUserIdFromToken();
      if (!userId) {
        return Promise.reject(new Error('User ID not found in token'));
      }
      applicationData.customerId = userId;
    }
    
    console.log(`Submitting application for user ID: ${applicationData.customerId}`);
    
    // Get the token
    const token = authService.getToken();
    if (!token) {
      return Promise.reject(new Error('No authentication token found'));
    }
    
    console.log(`Using token for submission: ${token.substring(0, 10)}...`);
    
    // Try using the api instance first
    return api.post(`${BASE_URL}/applications`, applicationData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    }).catch(error => {
      console.error('Error submitting application with api instance:', error);
      
      // Fallback to direct fetch with explicit token
      return fetch(`${BASE_URL}/applications`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(applicationData)
      }).then(response => {
        if (!response.ok) {
          throw new Error(`Failed to submit application: ${response.status}`);
        }
        return response.json().then(data => ({ data }));
      });
    });
  },
  
  // Extract user ID from token
  extractUserIdFromToken() {
    const token = authService.getToken();
    if (!token) return null;
    
    try {
      const tokenParts = token.split('.');
      if (tokenParts.length === 3) {
        const payload = JSON.parse(atob(tokenParts[1]));
        
        // Extract just the numeric ID from the sub field
        let userId = payload.sub || payload.id || '';
        
        // If the ID contains a comma, extract just the number part
        if (typeof userId === 'string' && userId.includes(',')) {
          userId = userId.split(',')[0].trim();
        }
        
        return userId;
      }
    } catch (error) {
      console.error('Error extracting user ID from token:', error);
    }
    return null;
  },
  
  // Get all account balances for a specific user
  getUserAccountBalances(userId) {
    const token = authService.getToken();
    if (!token) {
      return Promise.reject(new Error('No authentication token found'));
    }
    
    return fetch(`${BASE_URL}/user/${userId}/balances`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    }).then(response => {
      if (!response.ok) {
        throw new Error(`Failed to fetch account balances: ${response.status}`);
      }
      return response.json();
    });
  },

  // Get total balance for a specific user
  getUserTotalBalance(userId) {
    const token = authService.getToken();
    if (!token) {
      return Promise.reject(new Error('No authentication token found'));
    }
    
    return fetch(`${BASE_URL}/user/${userId}/total-balance`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    }).then(response => {
      if (!response.ok) {
        throw new Error(`Failed to fetch total balance: ${response.status}`);
      }
      return response.json();
    });
  },

  // Get all account types
  getAccountTypes() {
    const token = authService.getToken();
    if (!token) {
      return Promise.reject(new Error('No authentication token found'));
    }
    
    // Try using the api instance first (which should add the token via interceptor)
    return api.get(`${BASE_URL}/types`)
      .catch(error => {
        console.error('Error fetching account types with api instance:', error);
        
        // Fallback to direct fetch with explicit token if api instance fails
        return fetch(`${BASE_URL}/types`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        }).then(response => {
          if (!response.ok) {
            throw new Error(`Failed to fetch account types: ${response.status}`);
          }
          return response.json().then(data => ({ data }));
        });
      });
  },

  // Get pending account applications
  getPendingAccountApplications() {
    const token = authService.getToken();
    if (!token) {
      return Promise.reject(new Error('No authentication token found'));
    }
    const BankURL ='http://localhost:8085/api/bankdesk/';
    return api.get(`${BankURL}account-applications/pending`,  {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
  },

  // Update account applications status (approve/reject)
  updateAccountApplicationsStatus(requestData) {
    const BankURL ='http://localhost:8085/api/bankdesk/';
    const token = authService.getToken();
    if (!token) {
      return Promise.reject(new Error('No authentication token found'));
    }
    
    return api.put(`${BankURL}account-applications`, requestData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
  },
};

export default accountService;
